package com.yndsoft.jc.supplier.join;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.yndsoft.jc.R;
import com.yndsoft.jc.model.ReturnMsg;
import com.yndsoft.jc.supplier.base.SupplierBaseActivity;
import com.yndsoft.jc.supplier.modelput.Supplier;
import com.yndsoft.jc.supplier.net.util.ProgressSubscriber;
import com.yndsoft.jc.supplier.utils.Base64UploadImg;
import com.yndsoft.jc.supplier.utils.Constants;
import com.yndsoft.jc.supplier.utils.MaxLengthWatcher;
import com.yndsoft.jc.supplier.utils.RegexUtil;
import com.yndsoft.jc.supplier.utils.ToastUtil;
import com.yndsoft.jc.supplier.widget.dialog.SupplierDialog;
import com.yndsoft.jc.supplier.widget.imageselector.ImageLoader;
import com.yndsoft.jc.supplier.widget.imageselector.ImgSelActivity;
import com.yndsoft.jc.supplier.widget.imageselector.ImgSelConfig;
import com.yndsoft.jc.supplier.widget.popupwindow.OnChooseDataListener;

import java.util.List;

public class JoinInfoActivity extends SupplierBaseActivity implements View.OnClickListener, View.OnTouchListener {

    private EditText infoName;
    private EditText infoMail;
    private ImageView infoCardImg;
    private TextView infoBank;
    private TextView infoAli;
    private TextView infoWx;
    private TextView infoBankTitle;
    private EditText infoBankName;
    private EditText infoBankUser;
    private EditText infoBankAccount;
    private LinearLayout infoOther;
    private EditText infoOrg;
    private TextView infoSiteName;
    private EditText infoAddress;
    private ImageView infoLicenceImg;
    private EditText infoIntro;
    private LinearLayout infoRoot;
    private int collectStatus = 1; // 1支付宝 2微信 3银行
    private ImageLoader loader = new ImageLoader() {
        @Override
        public void displayImage(Context context, String path, ImageView imageView) {
            Glide.with(context)
                    .load(path)
                    .placeholder(R.drawable.ic_default_image)
                    .centerCrop()
                    .into(imageView);
        }
    };
    private String cardImgPath = null;
    private String licenceImgPath = null;
    private int provinceKey = 0;
    private String provinceValue = "";
    private int cityKey = 0;
    private String cityValue = "";
    private int districtKey = 0;
    private String districtValue = "";
    private String account;
    private String password;

    @Override
    public int getContentResId() {
        return R.layout.activity_join_info;
    }

    public static void start(Context context, String phone, String pwd) {
        Intent intent = new Intent(context, JoinInfoActivity.class);
        intent.putExtra(Constants.ACCOUNT, phone);
        intent.putExtra(Constants.PASSWORD, pwd);
        context.startActivity(intent);
    }

    @Override
    public void initView() {
        ImageButton barBack = findViewById(R.id.bar_back);
        TextView barTitle = findViewById(R.id.bar_title);
        infoName = findViewById(R.id.info_name);
        infoMail = findViewById(R.id.info_mail);
        infoCardImg = findViewById(R.id.info_card_img);
        RelativeLayout infoCard = findViewById(R.id.info_card);
        infoBank = findViewById(R.id.info_bank);
        infoAli = findViewById(R.id.info_ali);
        infoWx = findViewById(R.id.info_wx);
        infoBankTitle = findViewById(R.id.info_bank_title);
        infoBankName = findViewById(R.id.info_bank_name);
        infoBankUser = findViewById(R.id.info_bank_user);
        infoBankAccount = findViewById(R.id.info_bank_account);
        infoOther = findViewById(R.id.info_other);
        infoOrg = findViewById(R.id.info_org);
        infoSiteName = findViewById(R.id.info_site_name);
        LinearLayout infoSite = findViewById(R.id.info_site);
        infoAddress = findViewById(R.id.info_address);
        infoLicenceImg = findViewById(R.id.info_licence_img);
        RelativeLayout infoLicence = findViewById(R.id.info_licence);
        infoIntro = findViewById(R.id.info_intro);
        Button infoPut = findViewById(R.id.info_put);
        infoRoot = findViewById(R.id.info_root);

        barTitle.setText("机构入驻");
        barBack.setOnClickListener(this);
        infoCard.setOnClickListener(this);
        infoCardImg.setOnClickListener(this);
        infoBank.setOnClickListener(this);
        infoAli.setOnClickListener(this);
        infoWx.setOnClickListener(this);
        infoSite.setOnClickListener(this);
        infoLicence.setOnClickListener(this);
        infoLicenceImg.setOnClickListener(this);
        infoPut.setOnClickListener(this);
        infoIntro.setOnTouchListener(this);
        infoIntro.addTextChangedListener(new MaxLengthWatcher(500, infoIntro));
    }

    @Override
    public void initData() {
        account = getIntent().getStringExtra(Constants.ACCOUNT);
        password = getIntent().getStringExtra(Constants.PASSWORD);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bar_back:
                finish();
                break;
            case R.id.info_card:
            case R.id.info_card_img:
                chooseAlbum(Constants.REQUEST_CARD_CODE);
                break;
            case R.id.info_bank:
                collectStatus = 3;
                isCheck(infoBank, true);
                isCheck(infoAli, false);
                isCheck(infoWx, false);
                infoBankTitle.setText("开户行");
                infoBankName.setHint("请输入开户行名称");
                infoOther.setVisibility(View.VISIBLE);
                break;
            case R.id.info_ali:
                collectStatus = 1;
                isCheck(infoBank, false);
                isCheck(infoAli, true);
                isCheck(infoWx, false);
                infoBankTitle.setText("账号");
                infoBankName.setHint("请输入支付宝账号");
                infoOther.setVisibility(View.GONE);
                break;
            case R.id.info_wx:
                collectStatus = 2;
                isCheck(infoBank, false);
                isCheck(infoAli, false);
                isCheck(infoWx, true);
                infoBankTitle.setText("账号");
                infoBankName.setHint("请输入微信账号");
                infoOther.setVisibility(View.GONE);
                break;
            case R.id.info_site:
                PopupWindowAddress address = new PopupWindowAddress(mContext, infoSiteName.getText().toString());
                address.showAtLocation(infoRoot, Gravity.BOTTOM, 0, 0);
                address.setOnChooseDataListener(new OnChooseDataListener() {
                    @Override
                    public void onChooseData(int key1, String value1, int key2, String value2, int key3, String value3) {
                        infoSiteName.setText(value1 + " " + value2 + " " + value3);
                        infoSiteName.setTextColor(0xFF333333);
                        provinceKey = key1;
                        provinceValue = value1;
                        cityKey = key2;
                        cityValue = value2;
                        districtKey = key3;
                        districtValue = value3;
                    }
                });
                break;
            case R.id.info_licence:
            case R.id.info_licence_img:
                chooseAlbum(Constants.REQUEST_LICENCE_CODE);
                break;
            case R.id.info_put:
                String nameValue = infoName.getText().toString().trim();
                String mailValue = infoMail.getText().toString().trim();
                String bankNameValue = infoBankName.getText().toString().trim();
                String bankUserValue = infoBankUser.getText().toString().trim();
                String bankAccountValue = infoBankAccount.getText().toString().trim();
                String orgValue = infoOrg.getText().toString().trim();
                String addressValue = infoAddress.getText().toString().trim();
                String introValue = infoIntro.getText().toString().trim();
                if (TextUtils.isEmpty(nameValue)) {
                    showHint("请输入联系人姓名！");
                } else {
                    if (TextUtils.isEmpty(mailValue)) {
                        showHint("请输入联系人邮箱！");
                    } else {
                        if (!RegexUtil.isEmail(mailValue)) {
                            showHint("邮箱格式错误！");
                        } else {
                            if (null == cardImgPath) {
                                showHint("请上传负责人身份证！");
                            } else {
                                switch (collectStatus) {
                                    case 3: // 银行
                                        if (TextUtils.isEmpty(bankNameValue)) {
                                            showHint("请输入开户行名称");
                                        } else {
                                            if (TextUtils.isEmpty(bankUserValue)) {
                                                showHint("请输入银行开户名");
                                            } else {
                                                if (TextUtils.isEmpty(bankAccountValue)) {
                                                    showHint("请输入公司银行账号");
                                                } else {
                                                    nextHalf(nameValue, mailValue, bankNameValue, bankUserValue, bankAccountValue, orgValue, addressValue, introValue);
                                                }
                                            }
                                        }
                                        break;
                                    case 1: // 支付宝
                                        if (TextUtils.isEmpty(bankNameValue)) {
                                            showHint("请输入支付宝账号");
                                        } else {
                                            nextHalf(nameValue, mailValue, bankNameValue, null, null, orgValue, addressValue, introValue);
                                        }
                                        break;
                                    case 2: // 微信
                                        if (TextUtils.isEmpty(bankNameValue)) {
                                            showHint("请输入微信账号");
                                        } else {
                                            nextHalf(nameValue, mailValue, bankNameValue, null, null, orgValue, addressValue, introValue);
                                        }
                                        break;
                                }
                            }
                        }
                    }
                }
                break;
        }
    }

    private void nextHalf(String nameValue, String mailValue, String bankNameValue, String bankUserValue, String bankAccountValue, String orgValue, String addressValue, String introValue) {
        if (TextUtils.isEmpty(orgValue)) {
            showHint("请输入机构名称");
        } else {
            if ("".equals(provinceValue) && "".equals(cityValue) && "".equals(districtValue)) {
                showHint("请选择机构地址！");
            } else {
                if (TextUtils.isEmpty(addressValue)) {
                    showHint("请输入详细地址");
                } else {
                    if (null == licenceImgPath) {
                        showHint("请上传经营许可证！");
                    } else {
                        if (TextUtils.isEmpty(introValue)) {
                            showHint("请输入机构简介");
                        } else {
                            Supplier supplier = new Supplier();
                            supplier.setContactname(nameValue);
                            supplier.setEmail(mailValue);
                            supplier.setFrimg(cardImgPath);
                            supplier.setAccounttype(String.valueOf(collectStatus));
                            switch (collectStatus) {
                                case 3:
                                    supplier.setKhyhzh(bankNameValue);
                                    supplier.setYhkhm(bankUserValue);
                                    supplier.setGsyhzh(bankAccountValue);
                                    break;
                                case 1:
                                    supplier.setAlipay(bankNameValue);
                                    break;
                                case 2:
                                    supplier.setWeixinpay(bankNameValue);
                                    break;
                            }
                            supplier.setName(orgValue);
                            supplier.setProvinceid(String.valueOf(provinceKey));
                            supplier.setProvince(provinceValue);
                            supplier.setCityid(String.valueOf(cityKey));
                            supplier.setCity(cityValue);
                            supplier.setDistrictid(String.valueOf(districtKey));
                            supplier.setDistrict(districtValue);
                            supplier.setAddress(addressValue);
                            supplier.setYyzzimg(licenceImgPath);
                            supplier.setBusiness(introValue);
                            Supplier.SupplierAdmin admin = supplier.getAdmin();
                            admin.setPhone(account);
                            admin.setPwd(password);
                            String supplierJsonValue = new Gson().toJson(supplier);
                            putSupplierInfo(supplierJsonValue);
                        }
                    }
                }
            }
        }
    }

    private void putSupplierInfo(String json) {
        mHttpUtil.put(new ProgressSubscriber(mContext) {
            @Override
            public void next(ReturnMsg returnMsg) {
                if (1 == returnMsg.getCode()) {
                    JoinOkActivity.start(mContext);
                    finish();
                } else if (2 == returnMsg.getCode()) {
                    ToastUtil.show(mContext, "该手机号已存在!");
                } else {
                    ToastUtil.show(mContext, "提交失败!");
                }
            }
        }, "join", json);
    }

    private void chooseAlbum(int requestCode) {
        ImgSelConfig config = new ImgSelConfig.Builder(this, loader)
                .multiSelect(false)
                .rememberSelected(false)
                .needCamera(true)
                .maxNum(1)
                .build();
        ImgSelActivity.startActivity(this, config, requestCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            switch (requestCode) {
                case Constants.REQUEST_CARD_CODE:
                    List<String> cardPathList = data.getStringArrayListExtra(ImgSelActivity.INTENT_RESULT);
                    if (cardPathList != null && cardPathList.size() > 0) {
                        String path = cardPathList.get(0);
                        if (path != null) {
                            Glide.with(mContext).load("file://" + path).into(infoCardImg);
                            Base64UploadImg base64UploadImg = new Base64UploadImg();
                            base64UploadImg.uploadImg(mContext, path);
                            base64UploadImg.setOnUpImgListener(new Base64UploadImg.OnUpImgListener() {
                                @Override
                                public void onUpImg(String imgBase64) {
                                    cardImgPath = imgBase64;
                                }
                            });
                        }
                    }
                    break;
                case Constants.REQUEST_LICENCE_CODE:
                    List<String> licencePathList = data.getStringArrayListExtra(ImgSelActivity.INTENT_RESULT);
                    if (licencePathList != null && licencePathList.size() > 0) {
                        String path = licencePathList.get(0);
                        if (path != null) {
                            Glide.with(mContext).load("file://" + path).into(infoLicenceImg);
                            Base64UploadImg base64UploadImg = new Base64UploadImg();
                            base64UploadImg.uploadImg(mContext, path);
                            base64UploadImg.setOnUpImgListener(new Base64UploadImg.OnUpImgListener() {
                                @Override
                                public void onUpImg(String imgBase64) {
                                    licenceImgPath = imgBase64;
                                }
                            });
                        }
                    }
                    break;
            }
        }
    }

    private void isCheck(TextView textView, boolean isCheck) {
        Drawable drawable;
        if (isCheck) {
            drawable = getResources().getDrawable(R.mipmap.checked);

        } else {
            drawable = getResources().getDrawable(R.mipmap.unchecked);
        }
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        textView.setCompoundDrawables(drawable, null, null, null);
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (view.getId()) {
            case R.id.info_intro:
                view.getParent().requestDisallowInterceptTouchEvent(true);
                switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
                    case MotionEvent.ACTION_UP:
                        view.getParent().requestDisallowInterceptTouchEvent(false);
                        break;
                }
        }
        return false;
    }
}